﻿using MediatR;
using T.Common.Domain.Common;
using RedDragon.RBAC.API.Application.Common.Permission;
using AutoMapper;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.ErrorCodeEnum;
using RedDragon.Common.Dtos;
using SqlSugar;

namespace RedDragon.RBAC.API.Application.Common.UserRolePermission
{
    public class AddUserRoleHandler : IRequestHandler<AddUserRoleCommand, Result>
    {
        private readonly ISqlSugarClient db;
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 用户角色仓储
        /// </summary>
        public readonly IBaseRepository<UserRoles> userRolesRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<AddUserRoleHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="userRolesRepository"></param>
        /// <param name="logger"></param>
        public AddUserRoleHandler(ISqlSugarClient db, IMapper mapper, IBaseRepository<UserRoles> userRolesRepository, ILogger<AddUserRoleHandler> logger)
        {
            this.db = db;
            this.mapper = mapper;
            this.userRolesRepository = userRolesRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 用户角色添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(AddUserRoleCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var list = new List<UserRoles>();
                for (int i = 0; i < request.Roles.Count; i++)
                {
                    UserRoles dto = new UserRoles();
                    dto.RolesId = request.Roles[i];
                    dto.UserId = request.UserId;
                    list.Add(dto);
                }
                var res = userRolesRepository.AddRange(list);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "用户角色添加成功";
                }
            }
            catch (Exception ex)
            {
                logger.LogError("用户角色添加异常" + ex);
                result.Msg = "用户角色添加异常";
            }
            return result;
        }
    }
}
